package com.huluobo.a2110mvpimdemo.login;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.huluobo.a2110mvpimdemo.IMApp;
import com.huluobo.a2110mvpimdemo.MainActivity;
import com.huluobo.a2110mvpimdemo.R;
import com.huluobo.a2110mvpimdemo.base.BaseActivity;
import com.huluobo.a2110mvpimdemo.register.RegisterActivity;
import com.huluobo.a2110mvpimdemo.utils.SPUtils;
import com.hyphenate.chat.EMClient;

public class LoginActivity extends BaseActivity<LoginContract.View, LoginPresenter> implements LoginContract.View {

    private EditText username, password;

    @Override
    protected void initData() {
        presenter = new LoginPresenter();
    }

    @Override
    protected void initView() {
        username = findViewById(R.id.login_username);
        password = findViewById(R.id.login_password);
        Button toLogin = findViewById(R.id.login_toLogin);
        TextView toRegister = findViewById(R.id.login_toRegister);

        //从sp中取出之前记住的用户名
        if (SPUtils.getString(this, IMApp.SP_USERNAME, "").length() > 0) {
            username.setText(SPUtils.getString(this, IMApp.SP_USERNAME, ""));
        }

        //从s中取出之前记住的密码
        if (SPUtils.getString(this, IMApp.SP_PASSWORD, "").length() > 0) {
            password.setText(SPUtils.getString(this, IMApp.SP_PASSWORD, ""));
        }

        toLogin.setOnClickListener(v -> {
            presenter.login(username.getText().toString(), password.getText().toString());
        });


        toRegister.setOnClickListener(v -> {
            Intent intent = new Intent(this, RegisterActivity.class);
            startActivity(intent);
        });
    }

    @Override
    protected int bindLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void onLoginSuccess() {
        dismissProgressDialog();
        //登陆成功保存用户名
        SPUtils.putString(this, IMApp.SP_USERNAME, username.getText().toString());
        //登录成功保存密码
        SPUtils.putString(this, IMApp.SP_PASSWORD, password.getText().toString());
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onLoginFailed(String error) {
        dismissProgressDialog();
        Log.i("TagA", "登录失败:" + error);
    }

    @Override
    public void onUsernameError() {
        username.setError("用户名不符合规则,需要首字符为英文的3-20位字符");
    }

    @Override
    public void onPasswordError() {
        password.setError("密码不符合规则,,需要3-20位数字");
    }

    @Override
    public void onStartLogin() {
        //弹出进度条
        showProgressDialog("正在登录...");
    }
}